package com.app.oasystem.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.app.oasystem.constant.EventEnum;
import com.app.oasystem.constant.StaticParam;
import com.app.oasystem.entity.Event;
import com.app.oasystem.entity.User;
import com.app.oasystem.mapper.EventMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@WebFilter(filterName = "GlobalFilter", urlPatterns = "/*")
@Order(1)
@Slf4j
public class GlobalFilter implements Filter {
    @Resource
    EventMapper eventMapper;


    @Override
    public void init(FilterConfig config) throws ServletException {

    }


    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        String username = (String) request.getSession().getAttribute(StaticParam.SESSIONKEY_LOGIN_INFO);
        if (null != username) {
            Event event = new Event();
            String uri = request.getRequestURI();
            if (!(uri.contains(".js") || uri.contains(".css") || uri.contains("favicon.ico") || uri.contains("imageRandServlet"))) {
                for (EventEnum type : EventEnum.values()) {
                    if (uri.substring(6).matches(StaticParam.REGEX) && uri.contains(type.getUri())) {
                        event.setUri(uri);
                        event.setDescrible(type.getDescribe());
                    } else if (uri.equals(type.getUri())) {
                        event.setUri(type.getUri());
                        event.setDescrible(type.getDescribe());
                    } else if (uri.contains(type.getUri())) {
                        event.setUri(type.getUri());
                        event.setDescrible(type.getDescribe());
                    }
                }
                if (null != event.getUri()) {
                    event.setUsername(username);
                    String method = request.getMethod();
                    event.setMethod(method);
                    event.setCurrentTime(new Date());
                    eventMapper.insert(event);
                }
//                // 转换成代理类
//                ResponseWrapper wrapperResponse = new ResponseWrapper(response);
//                // 这里只拦截返回，直接让请求过去，如果在请求前有处理，可以在这里处理
//                chain.doFilter(req, wrapperResponse);
//                // 返回值字节
//                byte[] content = wrapperResponse.getContent();
//                // 判断是否有值
//                if (content.length <= 0) {
//                    ServletOutputStream out = response.getOutputStream();
//                    out.write(content);
//                    out.flush();
//                    event.setResponseContent("无响应内容...");
//                    log.error("无响应内容...");
//                    return;
//                }
//                // 返回值
//                String str = new String(content);
//                if (str.contains("obj")) {
//                    event.setResponseContent(str);
//                    log.error(str);
//                }
//                event.setCurrentTime(new Date());
//                //把返回值输出到客户端
//                ServletOutputStream out = response.getOutputStream();
//                out.write(content);
//                out.flush();
            }
        }
        chain.doFilter(req, resp);


    }

    @Override
    public void destroy() {
    }

    /**
     * 判断字符串数据是否为json
     *
     * @param content
     * @return
     */
    public static boolean isJson(String content) {
        try {
            JSON.parseObject(content);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}
